package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.FileService;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.ISpecificFunctionService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/system/specific_function")
public class SpecificFunctionController extends BaseController {
    @Value("${regulatedData.schema.path:/specific_function/schema}")
    private String schemaPath;

    @Autowired
    IDeviceService deviceService;

    @Autowired
    ISpecificFunctionService specificFunctionService;

    @PostMapping(value = "/call", produces = "application/json;charset=UTF-8")
    public AjaxResult call(@RequestParam("code") String code, @RequestBody JSONObject request) {
        code = code.toLowerCase();
        try {
            // TODO: [zy] check request with json schema
            if ("product_telemetry_increment".equals(code)) {
                return specificFunctionService.productTelemetryIncrement(request);
            } else if ("device_telemetry_increment".equals(code)) {
                return specificFunctionService.deviceTelemetryIncrement(request);
            }
        } catch (Exception e) {
            log.info("",e);
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return AjaxResult.success(request);
    }

    @PreAuthorize("@ss.hasPermi('system:specific_function:schema')")
    @GetMapping(value = "/schema", produces = "application/json;charset=UTF-8")
    public AjaxResult schema(@RequestParam("code") String code) {
        JSONObject schema = null;
        code = code.toLowerCase();
        String filePath = String.format("%s/%s.json", schemaPath, code);
        try {
            String content = FileService.load(filePath, false);
            schema = JSONObject.parseObject(content);
        } catch (Exception e) {
            log.info("",e);
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return AjaxResult.success(schema);
    }
}
